package com.pfzy.ui.activity.floatview;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pfzy.ui.R;
import com.pfzy.ui.utils.CheckPermissionUtils;

public class FloatSecurityCenterView {
    public static FloatSecurityCenterView floatView;
    private Context context;
    private WindowManager wm;
    private View view;// 浮动按钮
    private TextView tvStatus;
    private LinearLayout layoutAsecurityStatus;
    private ImageView imgType1;
    private ImageView imgType2;
    private int height = 0;
    private int width = 0;
    WindowManager.LayoutParams params;
    private View.OnClickListener listener;

    public static FloatSecurityCenterView getInstance(Context context) {
        if (floatView == null) {
            floatView = new FloatSecurityCenterView(context);
        }
        return floatView;
    }

    public FloatSecurityCenterView(Context context) {
        this.context = context;
    }

    public void createFloatView() {
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.security_center, null);
            tvStatus = view.findViewById(R.id.security_status);
            layoutAsecurityStatus = view.findViewById(R.id.security_status_layout);
            imgType1 = view.findViewById(R.id.security_type1);
            imgType2 = view.findViewById(R.id.security_type2);
        }

        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        height = wm.getDefaultDisplay().getHeight();
        width = wm.getDefaultDisplay().getWidth();

        params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;// 所有程序窗口的“基地”窗口，其他应用程序窗口都显示在它上面。
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.TRANSLUCENT;// 不设置这个弹出框的透明遮罩显示为黑色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP | Gravity.LEFT;

        int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        params.y = screenHeight - height / 3;// 设置距离底部高度为屏幕三分之一
        params.x = screenWidth;
        view.setBackgroundColor(Color.TRANSPARENT);
        view.setVisibility(View.VISIBLE);
        view.setOnTouchListener(new View.OnTouchListener() {
            // 触屏监听
            float lastX, lastY;
            int oldOffsetX, oldOffsetY;
            int tag = 0;// 悬浮球 所需成员变量

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int action = event.getAction();
                float x = event.getX();
                float y = event.getY();
                if (tag == 0) {
                    oldOffsetX = params.x; // 偏移量
                    oldOffsetY = params.y; // 偏移量
                }

                if (action == MotionEvent.ACTION_DOWN) {
                    lastX = x;
                    lastY = y;
                } else if (action == MotionEvent.ACTION_MOVE) {
                    params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动
                    params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动
                    tag = 1;
                    wm.updateViewLayout(view, params);
                } else if (action == MotionEvent.ACTION_UP) {
                    int newOffsetX = params.x;
                    int newOffsetY = params.y;
                    // 只要按钮一动位置不是很大,就认为是点击事件
                    if (Math.abs(oldOffsetX - newOffsetX) <= 20 && Math.abs(oldOffsetY - newOffsetY) <= 20) {
                        if (listener != null) {
                            listener.onClick(view);
                        }
                    } else {
                        if (params.x < width / 2) {
                            params.x = 0;
                        } else {
                            params.x = width;
                        }
                        wm.updateViewLayout(view, params);
                        tag = 0;
                    }
                }
                return true;
            }
        });

        try {
            wm.addView(view, params);
        } catch (Exception e) {
        }

        if (CheckPermissionUtils.getAppOps(context) && CheckPermissionUtils.isHasAudioRecordPermission(context) && CheckPermissionUtils.isLocServiceEnable(context)) {
            layoutAsecurityStatus.setVisibility(View.GONE);
        } else if (CheckPermissionUtils.getAppOps(context) && !CheckPermissionUtils.isLocServiceEnable(context)) {
            tvStatus.setText("定位未授权");
        } else if (CheckPermissionUtils.getAppOps(context) && !CheckPermissionUtils.isHasAudioRecordPermission(context)) {
            tvStatus.setText("录音未授权");
        }

        floatView.onFloatViewClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideFloatView();
            }
        });
    }

    /**
     * 将悬浮View从WindowManager中移除，需要与createFloatView()成对出现
     */
    public void removeFloatView() {
        if (wm != null && view != null) {
            wm.removeViewImmediate(view);
            // wm.removeView(view);//不要调用这个，WindowLeaked
            view = null;
            wm = null;
        }
    }

    /**
     * 隐藏悬浮View
     */
    public void hideFloatView() {
        if (wm != null && view != null && view.isShown()) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 显示悬浮View
     */
    public void showFloatView() {
        if (wm != null && view != null && !view.isShown()) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public Boolean isValid(){
        if (wm != null && view != null && !view.isShown()) {
            return true;
        }
        return false;
    }

    public void setType(int type){
        if(type==0){
            imgType1.setVisibility(View.VISIBLE);
            imgType2.setVisibility(View.GONE);
        }
        else{
            imgType2.setVisibility(View.VISIBLE);
            imgType1.setVisibility(View.GONE);
        }
    }

    /**
     * 点击浮动按钮触发事件，需要override该方法
     */
    public void onFloatViewClick(View.OnClickListener listener) {
        this.listener = listener;
    }
}
